#include "tmmediamanger.h"

#include "libMediaPusher.h"
#include "libEasyPlayerAPI.h"

TMMediaManger* gThis = NULL;
QSharedMemory* pSharedMem = NULL;

TMMediaManger::TMMediaManger()
{
    m_bStartRec = false;
    gThis = this;
    m_pPushHandle = NULL;
    m_pCapHandle = NULL;
    m_nPlayerChannel = NULL;

    m_pSettings = new QSettings("Config/Robot.ini", QSettings::IniFormat);
    m_pSettings->setIniCodec("UTF-8");
    m_pCodecAscii = QTextCodec::codecForName("GB18030");

    pSharedMem = new QSharedMemory("TamiRobot_Camera_Live");
    pSharedMem->create(1920*1080*3);
}

void MyMediaCapture_CB(int nType, char* pBuff, int nBuffLen, bool bKeyFrame)
{
    if (gThis->m_pPushHandle)
    {
        MediaPusher_PushCapData(gThis->m_pPushHandle, nType, pBuff, nBuffLen, bKeyFrame);
    }
}

void MyRawCapture_CB(int nType, char* pBuff, int nBuffLen, bool bKeyFrame)
{
    static int nCount = 0;
    nCount += 1;
    if( nCount > 6 ){ // 内存共享帧率控制，5fps
        nCount = 0;
    }else{
        return;
    }
    // Share Video RGB24 Data
    if( nType == 0 && pSharedMem){
        if( !pSharedMem->isAttached() ){
            pSharedMem->attach();
        }
        pSharedMem->lock();
        int* pMemData = (int*)pSharedMem->data();  // may be null
        pMemData[0] = gThis->m_vInfo.nWidth;
        pMemData[1] = gThis->m_vInfo.nHeight;
        memcpy((void*)(pMemData+2), (void*)pBuff, nBuffLen);
        pSharedMem->unlock();
    }
}

int __EasyPusher_Callback(int _id, EASY_PUSH_STATE_T _state, EASY_AV_Frame *_frame, void *_userptr)
{
    if (_state == EASY_PUSH_STATE_CONNECTING)               qDebug()<<("Connecting...");
    else if (_state == EASY_PUSH_STATE_CONNECTED)           qDebug()<<("Connected");
    else if (_state == EASY_PUSH_STATE_CONNECT_FAILED)      qDebug()<<("Connect failed");
    else if (_state == EASY_PUSH_STATE_CONNECT_ABORT)       qDebug()<<("Connect abort");
    //else if (_state == EASY_PUSH_STATE_PUSHING)             TRACE("P->\n");
    else if (_state == EASY_PUSH_STATE_DISCONNECTED)        qDebug()<<("Disconnect.");

    return 0;
}

void TMMediaManger::Init()
{
    m_pCapHandle = MediaCapture_Create();
    m_pPushHandle = MediaPusher_Create();

    int nVideoIndex = m_pSettings->value("Server/VideoIndex", 0).toInt();
    urlRtsp = m_pSettings->value("Server/Rtsp").toString();
    strMac = getHostMacAddress().replace(":","");

    int nEndPos = urlRtsp.lastIndexOf(":");
    int nStartPos = urlRtsp.indexOf("//");
    QString m_ip = urlRtsp.mid(nStartPos+2, nEndPos-nStartPos-2);
    int m_port = urlRtsp.right(urlRtsp.length()-nEndPos-1).toInt();
    //video

    m_vInfo.nIndex = nVideoIndex;
    m_vInfo.nWidth = 640;
    m_vInfo.nHeight = 480;
    m_vInfo.nFPS = 15;
    //audio
    MediaCaptureAudioInfo aInfo;
    aInfo.nIndex = 0;
    aInfo.nChannels = 2;
    aInfo.nSamplesPerSec = 44100; // 不支持16000
    aInfo.nBitsPerSample = 16;
    MediaCapture_Init(m_pCapHandle, &m_vInfo, &aInfo);

    //MediaCapture_SetCB(m_pCapHandle, MyMediaCapture_SaveFileCB, MyMediaCapture_SaveFileCB, false);
    //qDebug()<<"Create Handle:"<<m_pCapHandle<<m_pPushHandle;

    QThread::msleep(200);
    //推送
    MediaCapture_GetSPSAndPPS(m_pCapHandle, m_sps, m_spslen, m_pps, m_ppslen);
    MediaPusher_SetSPSAndPPS(m_pPushHandle, m_sps, m_spslen, m_pps, m_ppslen);

    qDebug()<<"MediaCapture_GetSPSAndPPS"<<m_pCapHandle<<m_sps<<m_spslen<<m_ppslen;

    MediaPusher_Init(m_pPushHandle, m_ip.toUtf8().data(),m_port, QString("%1_out.sdp").arg(strMac).toUtf8().data(), __EasyPusher_Callback);
    MediaCapture_SetCB(m_pCapHandle, MyMediaCapture_CB, MyMediaCapture_CB, false);
    MediaCapture_SetCB(m_pCapHandle, MyRawCapture_CB, NULL, true);

    EasyPlayer_Init();
}

void TMMediaManger::StartGuester()
{    
    //拉取
    QString strGetUrl = QString("%1/%2_in.sdp").arg(urlRtsp).arg(strMac);
    if(!m_nPlayerChannel){
        m_nPlayerChannel = EasyPlayer_OpenStream(strGetUrl.toUtf8().data(), NULL, DISPLAY_FORMAT_RGB24_GDI,
                                                 1, "admin", "admin", NULL, NULL);
        //EasyPlayer_SetShownToScale(m_nPlayerChannel, 0);

        EasyPlayer_SetFrameCache(m_nPlayerChannel, 3); //设置缓存
        EasyPlayer_PlaySound(m_nPlayerChannel);
    }
}

void TMMediaManger::StopGuester()
{
    if(m_nPlayerChannel){
        EasyPlayer_CloseStream(m_nPlayerChannel);
        m_nPlayerChannel = NULL;
    }
}

void TMMediaManger::Destroy()
{
    // Player
    StopGuester();
    EasyPlayer_Release();
    // Capture
    if( m_pCapHandle ){
        MediaCapture_SetCB(m_pCapHandle, NULL, NULL, false);
        MediaCapture_SetCB(m_pCapHandle, NULL, NULL, true);
        MediaCapture_Release(m_pCapHandle);
        m_pCapHandle = NULL;
    }
    // Pusher
    if( m_pPushHandle ){
        MediaPusher_Release(m_pPushHandle);
        m_pPushHandle = NULL;
    }
}

QString TMMediaManger:: getHostMacAddress()
{
    QList<QNetworkInterface> nets = QNetworkInterface::allInterfaces();// 获取所有网络接口列表
    int nCnt = nets.count();
    QString strMacAddr = "";
    for(int i = 0; i < nCnt; i ++)
    {
        // 如果此网络接口被激活并且正在运行并且不是回环地址，则就是我们需要找的Mac地址
        if(nets[i].flags().testFlag(QNetworkInterface::IsUp) && nets[i].flags().testFlag(QNetworkInterface::IsRunning) && !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack))
        {
            strMacAddr = nets[i].hardwareAddress();
            break;
        }
    }
    return strMacAddr;
}
